import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

// 系统自带， json.decode 就来自这个库，可以做数据解析
import 'dart:convert';



class SelfHttpRequest extends StatefulWidget {
  @override
  _SelfHttpRequestState createState() => _SelfHttpRequestState();
}

class _SelfHttpRequestState extends State<SelfHttpRequest> {
  List _list = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("http库请求数据"),
      ),
       // 浮动按钮，方便添加事件
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          http2();
        },
      ),
      // 把数据渲染到页面上
      body: ListView.builder(
        itemCount: _list.length,
        itemBuilder: (BuildContext context, int i) {
          return Text('${_list[i]["nm"]}');
        },
      ),
    );
  }

  http1() async {
    String url = 'http://m.maoyan.com/ajax/movieOnInfoList?token=';
    // 使用 http.get 这个方法请求数据，因为数据是异步的，所以需要用到  async await，得到的response有固定的类型
    http.Response response = await http.get(url);
    // json.decode是用来做数据解析的，把字符串解析成对象/键值对
    // response.body 是字符串类型，当然是这个http请求库帮我们封装的
    Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData["movieList"]);
    setState(() {
      // 动态改变state数据，帮我们渲染到页面上
      _list = responseData["movieList"];
    });
  }

  http2() {
    // 用了 .then 的方法处理了异步请求
    String url = 'http://m.maoyan.com/ajax/movieOnInfoList?token=';
    http.get(url).then((http.Response response) {
      Map<String, dynamic> responseData = json.decode(response.body);
      print(responseData["movieList"]);
      setState(() {
        _list = responseData["movieList"];
      });
    });
  }
}
